using System;
using UnityEngine;

namespace Utils
{
    public class Timer
    {
        public bool IsActive => _timer > 0f;
        public float Value => _timer;
        
        private readonly Action _actionOnEnded;
        private float _duration;
        private float _timer;
        
        
        public Timer(float duration, Action actionOnEnded = null)
        {
            _duration = duration;
            _actionOnEnded = actionOnEnded;
        }

        /// <summary>
        /// 让时间流逝，归零时触发action
        /// </summary>
        public void Tick()
        {
            if (!IsActive) return;
            
            _timer -= Time.deltaTime;
            if (_timer <= 0f)
            {
                _actionOnEnded?.Invoke();
            }
        }
        
        /// <summary>
        /// 重置为初始时间
        /// </summary>
        public void Reset()
        {
            _timer = _duration;
        }

        public void Reset(float newDuration)
        {
            _duration = newDuration;
            Reset();
        }
        
        public override string ToString()
        {
            return $"Timer {_timer} / {_duration}";
        }
    }
}